package br.com.future;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class SecurityContextUtils {

	private static final String HEADER_SECUTIRY_CONTEXT = "Future-x-header-Secutiry-context";

	@SuppressWarnings("unchecked")
	public static void extractHeadersFromRequest(HttpServletRequest request) {
		SecurityContext sc = getSecurityContextFromRequest(request);
		Enumeration<String> en = request.getHeaderNames();
		while (en.hasMoreElements()) {
			String headerName = en.nextElement();
			sc.addHeader(headerName, request.getHeader(headerName));
		}
	}

	private static SecurityContext getSecurityContextFromRequest(HttpServletRequest request) {
		checkSecurityContextFromRequest(request);
		return (SecurityContext) request.getAttribute(HEADER_SECUTIRY_CONTEXT);
	}

	private static void checkSecurityContextFromRequest(HttpServletRequest request) {
		if (null == request.getAttribute(HEADER_SECUTIRY_CONTEXT)) {
			System.out.println("SecurityContext not found on request, creating...");
			request.setAttribute(HEADER_SECUTIRY_CONTEXT, SecurityContext.getInstance());
		}
		System.out.println("SecurityContext found on request!");
	}
}
